<!-- 
    @file: 登录页验证码组件
    @auth: lizibin
 -->
<template>
    <div class="ValidCode disabled-select" :style="`width:${width}; height:${height};padding:0px 10px;`"
        @click="refreshCode">
        <span v-for="(item, index) in state.codeList" :key="index" :style="getStyle(item)">{{ item.code }}</span>
    </div>
</template>

<script setup lang="ts">
import {
    reactive,
    onMounted
} from 'vue'
// 子传父
const emit = defineEmits(['getVerificationCode'])
// 接收父组件的值 TS特有写法
type Props = {
    width?: string,
    height?: string,
    length?: number,
}
const props = withDefaults(defineProps<Props>(), {
    width: '80px',
    height: '34px',
    length: 4,
})
type State = {
    codeList: any[]
}
let state = reactive<State>({
    codeList: []
})
onMounted(() => {
    createdCode();
});
const refreshCode = () => {
    createdCode();
};
const createdCode = () => {
    const len = props.length
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789'
    const charsLen = chars.length
    let list = []
    // 生成
    for (let i = 0; i < len; i++) {
        const rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math
            .random() * 200)]
        list.push({
            code: chars.charAt(Math.floor(Math.random() * charsLen)),
            color: `rgb(${rgb})`,
            fontSize: `1${[Math.floor(Math.random() * 10)]}px`,
            padding: `${[Math.floor(Math.random() * 10)]}px`,
            transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 90)}deg)`
        })
    }
    // 指向
    state.codeList = list
    // 将当前数据派发出去
    emit('getVerificationCode', state.codeList.map(item => item.code).join(''))
}
const getStyle = (data: any) => {
    return `color: ${data.color}; font-size: ${data.fontSize}; padding: ${data.padding}; transform: ${data.transform}`
}
defineExpose({
	refreshCode
})
</script>

<style scoped>
.ValidCode {
    user-select: none;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.ValidCode span {
    display: inline-block;
}
</style>